package com.auto.finance.auth.collect;

import com.auto.finance.auth.collect.support.FeignRestTemplateReporter;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author tianye
 */
@Configuration
@EnableConfigurationProperties(CollectProperties.class)
@ConditionalOnClass(ApiCollectService.class)
public class CollectAutoConfiguration {

    public static final String REPORT_THREAD_POOL_NAME = "authReportThreadPool";

    @Bean
    @ConditionalOnMissingBean(ApiCollectService.class)
    public ApiCollectService apiCollectService(CollectProperties properties) {
        return new ApiCollectService().setProperties(properties);
    }

    @Bean
    public FeignRestTemplateReporter feignRestTemplateReporter(CollectProperties properties) {
        return new FeignRestTemplateReporter().setProperties(properties);
    }

    @Bean("reportRestTemplate")
    @LoadBalanced
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        // 解决中文乱码
        List<HttpMessageConverter<?>> converterList = restTemplate.getMessageConverters();
        HttpMessageConverter<?> converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        converterList.add(0, converter);
        return restTemplate;
    }

    @Bean(name = REPORT_THREAD_POOL_NAME)
    public ExecutorService executorService() {
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                .setNameFormat("auth-report-thread-%d").build();
        return new ThreadPoolExecutor(
                1,
                2,
                0,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(2),
                namedThreadFactory
        );
    }
}
